<!--
 * @Description:
 * @Author: william
 * @Date: 2025-02-17 16:47:40
 * @LastEditors: william
 * @LastEditTime: 2025-08-30 10:41:51
-->
<template>
  <BaseDialog
    v-model="dialogVisible"
    :title="title"
    style="width: 550px"
    width="550px"
    :before-close="handleClose"
  >
    <el-form
      ref="refDialogForm"
      v-loading="formLoading"
      class="set-dialog-form"
      :label-width="language === 'en' ? '180px' : '85px'"
      :model="formData"
      :rules="rules"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('fleet.departure')" prop="startRegionCode">
            <CascaderArea
              v-model="formData.startRegionCode"
              style="width: 100%"
              :label="$t('fleet.departure')"
              :level="2"
              @change="handleRegionChange('1', $event)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('public.departure')" prop="startAddress">
            <span style="display: flex; align-items: center; flex: 1">
              <TextInput
                v-model="formData.startAddress"
                :placeholder="
                  g_rules.zhAndEnShowMsg(
                    $t('public.pleaseSelect'),
                    $t('public.departure')
                  )
                "
                @input="handleAddressChange('1')"
              />
              <el-button text @click="handleMapSelect('1')">{{
                $t('public.map')
              }}</el-button>
            </span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('fleet.destination')" prop="endRegionCode">
            <CascaderArea
              v-model="formData.endRegionCode"
              style="width: 100%"
              :label="$t('fleet.destination')"
              :level="2"
              @change="handleRegionChange('2', $event)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('public.destination')" prop="endAddress">
            <span style="display: flex; align-items: center; flex: 1">
              <TextInput
                v-model="formData.endAddress"
                :placeholder="
                  g_rules.zhAndEnShowMsg(
                    $t('public.pleaseSelect'),
                    $t('public.destination')
                  )
                "
                @input="handleAddressChange('2')"
              />
              <el-button text @click="handleMapSelect('2')">{{
                $t('public.map')
              }}</el-button>
            </span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('fleet.departureTime')" prop="startTime">
            <DateTimeLimit
              v-model="formData.startTime"
              time-point-type="start"
              :time-boundary="formData.endTime"
              style="width: 100%; max-width: 100%"
              :label="$t('fleet.departureTime')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('public.endTime')" prop="endTime">
            <DateTimeLimit
              v-model="formData.endTime"
              time-point-type="end"
              :time-boundary="formData.startTime"
              style="width: 100%; max-width: 100%"
              :label="$t('public.endTime')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('public.remark')" prop="note">
            <TextInput
              v-model="formData.note"
              type="textarea"
              :rows="2"
              :label="$t('public.remark')"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="form-dialog-footer">
        <el-button plain @click="handleClose">{{
          $t('public.cancel')
        }}</el-button>
        <el-button type="primary" @click="handleSubmitForm">{{
          $t('public.confirm')
        }}</el-button>
      </div>
    </template>
    <SearchMap
      v-if="searchMapVisible"
      v-model="searchMapVisible"
      :type="searchMapType"
      :regionName="regionName"
      @add="handleAddRegion"
    />
  </BaseDialog>
</template>

<script setup>
const props = defineProps({
  type: {
    type: String,
    default: 'add' // add | edit
  },
  vehicleId: {
    type: String,
    default: ''
  },
  id: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update'])
const dialogVisible = defineModel({
  type: Boolean,
  default: false
})
const { language } = storeToRefs(useAppStore())
const title = computed(() =>
  props.type === 'add' ? g_t('public.create') : g_t('public.edit')
)

const refDialogForm = ref(null)
const formLoading = ref(false)
const formData = ref({
  startRegionCode: '',
  startAddress: '',
  startLocation: {
    lng: '',
    lat: ''
  },
  endRegionCode: '',
  endAddress: '',
  endLocation: {
    lng: '',
    lat: ''
  },
  startTime: '',
  endTime: '',
  orderId: '',
  note: ''
})
const rules = {
  startRegionCode: g_rules.selectRule(g_t('fleet.departure')),
  startAddress: g_rules.selectRule(g_t('public.departure')),
  endRegionCode: g_rules.selectRule(g_t('fleet.destination')),
  endAddress: g_rules.selectRule(g_t('public.destination')),
  startTime: g_rules.selectRule(g_t('fleet.departureTime')),
  endTime: g_rules.selectRule(g_t('public.endTime'))
}
const searchMapVisible = ref(false)
const searchMapType = ref('')
const regionName = ref('')

onMounted(() => {
  props.type === 'edit' && getFormData()
})

const getFormData = () => {
  g_api.fleet
    .apiScheduleDetail({
      vehicleScheduleId: props.id
    })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        g_utils.assignFormData(formData.value, data)
        formData.value.vehicleScheduleId = data.id
        console.log('formData.value', formData.value)
      }
    })
}

const handleClose = () => {
  dialogVisible.value = false
}

const handleRegionChange = (type, data) => {
  // console.log('handleRegionChange', type, data)
  formData.value[type == '1' ? 'startRegionCode' : 'endRegionCode'] =
    data.lastCode
  getLocation(type)
}

const handleAddressChange = type => {
  // console.log('handleAddressChange', type, formData.value.startAddress)
  getLocation(type)
}

// 根据全路径名称获取经纬度
const getLocation = g_.debounce(async type => {
  const prefix = type == '1' ? 'start' : 'end'
  const regionCode = formData.value[`${prefix}RegionCode`]
  const address = formData.value[`${prefix}Address`]
  if (regionCode && address) {
    formData.value[`${prefix}Location`] = await g_utils.getAMapLocation(
      g_utils.getRegionName(regionCode) + address
    )
  } else {
    formData.value[`${prefix}Location`] = {
      lng: '',
      lat: ''
    }
  }
  console.log(`${prefix}Location`, formData.value[`${prefix}Location`])
}, 300)

const handleMapSelect = type => {
  searchMapVisible.value = true
  searchMapType.value = type
  // 获取对应类型的区域编码和地址
  const { startRegionCode, startAddress, endRegionCode, endAddress } =
    formData.value
  const [regionCode, address] =
    type === '1' ? [startRegionCode, startAddress] : [endRegionCode, endAddress]
  regionName.value = g_utils.getRegionName(regionCode, '') + address
}

const handleAddRegion = (type, data) => {
  // console.log('handleAddRegion', type, data)
  const { regionCode, address, lnglat } = data
  const prefix = type === '1' ? 'start' : 'end'

  formData.value[`${prefix}RegionCode`] = regionCode[regionCode.length - 1]
  formData.value[`${prefix}Address`] = address
  formData.value[`${prefix}Location`] = {
    lng: lnglat[0],
    lat: lnglat[1]
  }
  refDialogForm.value.validateField(`${prefix}RegionCode`)
}

const handleSubmitForm = () => {
  if (formLoading.value) return
  refDialogForm.value.validate(valid => {
    console.log('formData.value', formData.value)
    if (!valid) return
    formLoading.value = true
    const urlMethod =
      props.type === 'add'
        ? g_api.fleet.apiScheduleCreate
        : g_api.fleet.apiScheduleUpdate
    urlMethod({
      ...formData.value,
      vehicleId: props.type === 'add' ? props.vehicleId : undefined,
      orderId: ''
    })
      .then(res => {
        if (res.code === '200') {
          ElMessage({
            message: res.message,
            type: 'success'
          })
          handleClose()
          emit('update')
        }
      })
      .finally(() => {
        formLoading.value = false
      })
  })
}
</script>

<style scoped lang="scss"></style>
